<template>
  <section>
    <el-tabs v-model="activeName"
             @tab-click="handleClick">
      <el-tab-pane label="共用跟踪方式"
                   name="first">
        <div class="tips">
          <icon-svg icon-name="tishi1"
                    style="width:14px; height:14px;" />
          确定后，后台要进行每单绑定，页面显示跟踪信息需要一定时间，请耐心等待。
        </div>
        <el-form ref="ruleForm"
                 v-loading="boxLoading"
                 element-loading-text="拼命加载中"
                 element-loading-spinner="el-icon-loading"
                 class="form-style"
                 :model="ruleForm"
                 label-width="90px">
          <number-type v-if="!boxLoading"
                       :form-info="ruleForm"
                       :transport-type="transportType" />
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="不共用跟踪方式"
                   name="second">
        <div class="tips">
          <icon-svg icon-name="tishi1"
                    style="width:14px; height:14px;" />
          确定后，后台要进行每单绑定，页面显示跟踪信息需要一定时间，请耐心等待。
        </div>
        <div class="tab-box">
          <el-tabs v-model="subActiveName"
                   type="border-card">
            <el-tab-pane label="默认"
                         name="default">
              <BatchBindRow v-if="subActiveName === 'default'"
                            v-model="defaultValue"
                            :name="subActiveName"
                            @delete="deleteRow"
                            @handleInput="handleInput" />
            </el-tab-pane>
            <el-tab-pane label="粘贴文本识别"
                         name="paste">
              <el-row :gutter="20"
                      class="form-style">
                <el-col :span="21">
                  <el-input v-model="text"
                            type="textarea"
                            show-word-limit
                            :placeholder="placeholder"
                            maxlength="1000"
                            :rows="4" />
                </el-col>
                <el-col :span="2">
                  <el-button type="primary"
                             :disabled="!text"
                             :loading="identifyLoading"
                             @click="handleIdentify">识别</el-button>
                </el-col>
              </el-row>
              <BatchBindRow v-if="subActiveName === 'paste'"
                            v-model="bindDeviceData"
                            :name="subActiveName"
                            :scroll-bar-height="scrollBarHeight"
                            @delete="deleteRow"
                            @handleInput="handleInput" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div v-if="!boxLoading"
         class="footer-button">
      <el-button type="default"
                 @click="handleCancel">取消</el-button>
      <el-button type="primary"
                 :loading="loading"
                 @click="handleSubmit('ruleForm')">{{
          loading ? "提交中 ..." : "确 定"
        }}</el-button>
    </div>
  </section>
</template>

<script>
import numberType from "@components/numberType/index";
import BatchBindRow from "./BatchBindRow.vue"
import { dialogFulfill } from '@tablra/fulfill/executors/RequestExecutor'
import { mapState, mapActions } from "vuex";
import { order } from '@/api/index'
import axios from 'axios';

const HEADER_ROW = { contractNo: '合同编号', deviceCode: '跟踪方式', trackTypeDesc: '设备编号' }

export default {
  name: "TrackBatchBind",
  components: {
    numberType,
    BatchBindRow
  },
  inheritAttrs: true,
  props: {
    value: {
      type: Object,
      default: () => { }
    },
    query: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      code: '35160808',
      activeName: 'first',
      placeholder: '粘贴文本（合同编号 设备编号后七位）\n示例：\nzd-613001   6050300\nzd-613002   6050300',
      loading: false,
      identifyLoading: false,
      boxLoading: true,
      ruleForm: {
        trackType: 1,
        deviceCode: null
      },
      subActiveName: "default",
      // disabled: false,
      defaultValue: [],
      text: null,
      bindDeviceData: []
    }
  },
  computed: {
    ...mapState({
      batchBindId: (state) => state.batch.batchBindId,
    }),
    scrollBarHeight () {
      return "185px"
    },
    transportType () {
      return this.query?.transportType;
    },
    bindType () {
      return this.query?.bindType; // 1订单 2运单
    },
    orderIds () {
      return this.query?.orderIds || [];
    },
    waybillIds () {
      return this.query?.waybillIds || [];
    },
    selections () {
      return this.query?.selections || []
    },
    url () {
      return this.activeName === 'first' ? this.query.batchUrl : this.query.url
    },
    method () {
      return this.bindType === "1" && this.activeName === "second" ? 'put' : 'post'
    },
    idCountExceeded () {
      return this.selections?.length || 0
    },
    taskUrl () {
      return `/tenant/task/{id}`
    },
    processItems () {
      return (items, idKey) => items.reduce((result, item1) => {
        const found = this.selections.find(item2 => item1.contractNo === item2.contractNo);
        if (found) {
          result.matched.push({ ...item1, [idKey]: found[idKey] });
        } else {
          result.unmatched.push({ ...item1, errorMessage: '合同编号不存在' });
        }
        return result;
      }, { matched: [], unmatched: [] });
    }
  },
  watch: {
    value: {
      handler (value) {
        this.$nextTick(() => {
          this.activeName = 'first'
          this.ruleForm.deviceCode = null
          this.ruleForm.trackType = 1
          this.boxLoading = false
        })
      },
      immediate: true
    }
  },
  mounted () {
    this.loadDefaultValue(this.bindType)
  },
  methods: {
    ...mapActions({
      setbatchBindId: "batch/setbatchBindId",
    }),
    handleClick (tab, event) {
      console.log(tab, event);
    },
    handleCancel () {
      this.$emit("cancel");
    },
    loadDefaultValue (bindType) {
      const records = [HEADER_ROW, ...this.selections];
      const idField = bindType === '1' ? 'orderId' : 'waybillId';
      this.defaultValue = records.map(({ contractNo, orderId, waybillId, deviceCode, trackTypeDesc }, index) => {
        return {
          contractNo, deviceCode, trackTypeDesc,
          ...(index === 0 ? {} : {
            [idField]: bindType === '1' ? (orderId || null) : (waybillId || null),
            deviceCode: null,
            errors: "",
            trackTypeDesc: '电子回单',
            trackType: 1
          })
        };
      });
    },
    async processAndHandleItems (textRows, key) {
      const { matched, unmatched } = this.processItems(textRows, key);

      const promises = matched.map(async item => {
        const params = { ...item, deviceCode: `${this.code}${item.deviceCode}` };
        const bindCallback = await this.handleDeviceBind(params);
        return {
          ...item,
          errors: bindCallback?.errors || ""
        };
      });

      const matchedBind = await Promise.all(promises);

      this.bindDeviceData = [HEADER_ROW, ...matchedBind, ...unmatched];

      console.log('Matched:', matched);
      console.log('Unmatched:', unmatched);
    },

    async handleIdentify () {
      if (!this.text) {
        this.bindDeviceData = [];
        return;
      }
      this.identifyLoading = true;
      // 粘贴文本
      const textRows = this.getPastedText()
      if (this.bindType === "1") {
        this.processAndHandleItems(textRows, 'orderId')

      } else {
        this.processAndHandleItems(textRows, 'waybillId')
      }
      this.identifyLoading = false;
    },
    getPastedText () {
      // 获取粘贴文本
      const result = this.text.split('\n').map(line => {
        const [contractNo, deviceCode] = line.trim().split(/\s+/); // 去除首尾空格并分割每行文本
        return { contractNo, deviceCode, trackTypeDesc: '电子回单', trackType: 1 }; // 构建对象
      });
      return result
    },
    deleteRow (index) {
      this.bindDeviceData.splice(index, 1);
    },
    async handleDeviceBind (data) {
      let response = await order.restrictDevice(data)
      if (response.code === 0) {
        return response.data
      }
    },
    async handleInput (value, indx) {
      if (!this.updateError(value, indx)) return

      const { errors: _, ...args } = value
      const params = { ...args, deviceCode: `${this.code}${value.deviceCode}` }

      let bindCallback = await this.handleDeviceBind(params)

      const currentCore = this.subActiveName === 'default'
        ? this.defaultValue
        : this.bindDeviceData

      const idToFind = this.bindType === '1' ? 'orderId' : 'waybillId';
      const index = currentCore.findIndex(item => item[idToFind] === bindCallback[idToFind]);

      if (index !== -1) {
        this.$set(this.defaultValue, index, { ...value, errors: bindCallback.errors });
      }
    },
    handleSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.activeName === 'first') {
            this.handleTrack({ ...this.ruleForm })
          } else {
            if (this.subActiveName === 'default') {
              const [, ...newArray] = this.defaultValue
              const filterDefaultValue = newArray.filter(item => item.deviceCode)
              if (!filterDefaultValue.length) {
                this.$message.warning("请最少输入一条设备")
                return
              }
            } else {
              if (!this.bindDeviceData.length) {
                this.$message.warning("请最少输入一条设备")
                return
              }
            }
            this.circulateTrack()
          }
        } else {
          return false;
        }
      });
    },
    // 共用
    handleTrack (params) {
      if (!params.deviceCode) {
        return this.$message.error(`${params.trackType === 1 ? '请选择电子回单！' : '请输入快递单号！'}`)
      }
      this.loading = true;
      let deviceCode = params.trackType === 1 ? (params.deviceCode ? `${this.code}${params.deviceCode}` : null) : params.deviceCode;
      if (this.bindType === "1") {
        this.actionDispatch({ orderIds: this.orderIds, name: "批量绑定", routes: [], trackNo: deviceCode, trackType: params.trackType });
      } else {
        this.actionDispatch({ waybillIds: this.waybillIds, name: "批量绑定", deviceDTO: { deviceCode, trackType: params.trackType, transports: [] } });
      }
    },
    // 不共用
    async circulateTrack () {
      if (this.subActiveName === 'default') {
        if (!this.validationDefaultSubmit()) {
          return this.$message.warning("请修正报错内容")
        }
        await this.callActionDispatch(this.defaultValue)
      } else {
        if (!this.validationPasteSubmit()) {
          return this.$message.warning("请修正报错内容")
        }
        await this.callActionDispatch(this.bindDeviceData)
      }
      this.loading = false
      this.$emit("confirm");
      this.$message({ type: "success", message: "操作成功" });
    },
    updateError (value, index) {
      if (!value.deviceCode && (this.subActiveName === 'default' || this.subActiveName === 'paste')) {
        const targetArray = this.subActiveName === 'default'
          ? this.defaultValue
          : this.bindDeviceData;
        this.$set(targetArray, index, { ...value, errors: "" });
        return false;
      }
      return true;
    },

    validationDefaultSubmit () {
      const found = this.defaultValue.find(found =>
        found?.errors);
      return found ? false : true
    },
    validationPasteSubmit () {
      const found = this.bindDeviceData.find(found =>
        found?.errors && found?.errorMessage);
      return found ? false : true
    },
    async callActionDispatch (afferValue) {
      const filterValue = afferValue.filter(({ orderId, waybillId, deviceCode }) =>
        (orderId || waybillId) && deviceCode);

      const promises = filterValue.map(async (item, index) => {
        let params;
        if (item.orderId) {
          params = { orderId: item.orderId, trackType: 1, trackNo: `${this.code}${item.deviceCode}`, routes: [] };
        } else if (item.waybillId) {
          params = { waybillId: item.waybillId, deviceDTO: { ...item, deviceCode: `${this.code}${item.deviceCode}`, transports: [] } };
        }

        if (params) {
          await this.delay(index * 1000); // 设置1秒的时间间隔
          const promise = await this.bindDeviceCode(params);
          return promise;
        }
      });

      const results = await Promise.all(promises);
      return results[results.length - 1];
    },
    async bindDeviceCode (params) {
      this.loading = true;
      let response = await axios[this.method](this.url, params)
      if (response?.code === 0) {
        return { data: true }
      }
    },
    async delay (ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    async actionDispatch (params) {
      const response = await this.wereBatchBind(params)
      this.loading = false;
      this.text = null;
      this.bindDeviceData = [];
      this.setbatchBindId(response)
      if (this.batchBindId) {
        this.handleIdCountExceeded(response);
      }
      // this.$emit("confirm");
      // this.$message({ type: "success", message: "操作成功" });
    },
    async wereBatchBind (params) {
      try {
        let response = await axios[this.method](this.url, params)
        if (response?.code === 0) {
          if (!response?.data) {
            this.loading = false
            this.$emit("confirm");
            this.$message({ type: "success", message: "操作成功" });
          }
          return response?.data;
        } else {
          this.loading = false
          this.$message({ type: "error", message: response?.message });
        }
      } catch {
        this.loading = false
      }
    },
    handleIdCountExceeded (data) {
      this.$emit("cancel");
      const component = {
        taskUrl: this.taskUrl,
        count: this.idCountExceeded,
        name: `批量绑定`,
        id: data || this.batchBindId
      };
      dialogFulfill.invoke(component);
    }
  }
}
</script>
<style scoped>
.form-style {
  min-height: 60px;
  margin-top: 10px;
  margin-bottom: 15px;
}
.footer-button {
  display: flex;
  justify-content: flex-end;
}
.flex-start {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.rowSty {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 12px 5px;
}
.tab-box {
  padding-bottom: 15px;
}
.content {
  max-height: 360px;
  overflow-x: hidden;
}
.tips {
  font-size: 12px;
  color: var(--prev-color-primary);
  margin-bottom: 12px;
}
</style>